package cn.ljy.mes.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.ljy.authority.config.security.UserUtil;
import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.mes.dao.mapper.*;
import cn.ljy.mes.model.MesCarTechnology;
import cn.ljy.mes.model.MesProductionOrder;
import cn.ljy.mes.model.MesProductionOrderAuditLog;
import cn.ljy.mes.model.ShopCarOrder;
import cn.ljy.mes.model.common.MesConstant;
import cn.ljy.mes.model.query.MesCarTechnologyQuery;
import cn.ljy.mes.model.query.MesProductionOrderQuery;
import cn.ljy.mes.model.query.MesProductionOrderStepQuery;
import cn.ljy.mes.model.query.ShopCarOrderQuery;
import cn.ljy.mes.service.MesProductionOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IMesProductionOrderService extends IBaseService<MesProductionOrder, MesProductionOrderQuery> implements MesProductionOrderService {

    @Autowired
    private MesProductionOrderMapper mapper;
    @Autowired
    private MesProductionOrderAuditLogMapper productionOrderAuditLogMapper;
    @Autowired
    private MesProductionOrderStepMapper productionOrderStepMapper;
    @Autowired
    private ShopCarOrderMapper carOrderMapper;
    @Autowired
    private ShopCarProductMapper carProductMapper;
    @Autowired
    private MesCarModelConfigMapper carModelConfigMapper;
    @Autowired
    private MesCarModelMapper carModelMapper;
    @Autowired
    private MesCarTechnologyMapper carTechnologyMapper;

    @Override
    protected void enrichEntityFields(MesProductionOrder productionOrder){
        if(productionOrder!=null){
            //获取车型

        }
    }

    @Override
    protected void afterGet(MesProductionOrder productionOrder) {
        //获取生产步骤
        MesProductionOrderStepQuery productionOrderStepQuery=new MesProductionOrderStepQuery();
        productionOrderStepQuery.setProductionOrder(productionOrder);
        productionOrder.setSteps(productionOrderStepMapper.findAll(productionOrderStepQuery));
    }

    @Override
    protected void beforeSave(MesProductionOrder productionOrder) {
        //验证订单信息
        if(productionOrder.getShopCarOrder().getId()==null){
            throw new MyWebException("验证失败：订单id不能为空");
        }
        //根据订单信息获取车型配置
        ShopCarOrder carOrder = carOrderMapper.findById(productionOrder.getId());
        if(carOrder==null){
            throw new MyServiceException("验证失败：商城订单不存在！");
        }
        productionOrder.setCarModelConfig(carOrder.getCarModelConfig());
        //根据车型配置获取当前启用的生产工艺
    }

    @Override
    public int createProductionOrdersByShopCarOrder() {
        int result=0;
        //1.获取所有确定状态的商城订单
        ShopCarOrderQuery carOrderQuery=new ShopCarOrderQuery();
        carOrderQuery.setOrderStatus("confirmed");
        List<ShopCarOrder> carOrders = carOrderMapper.findAll(carOrderQuery);
        //2.生成生产订单
        if(carOrders.size()>0){
            List<MesProductionOrder> productionOrders=new ArrayList<>();//定义生产订单集合
            MesProductionOrder productionOrder;
            for(ShopCarOrder carOrder:carOrders){
                productionOrder=new MesProductionOrder();
                productionOrder.setId(IdUtil.simpleUUID());
                productionOrder.setShopCarOrder(carOrder);
                productionOrder.setCarModelConfig(carOrder.getCarModelConfig());
                productionOrder.setVin(IdUtil.simpleUUID());//生成vin，暂时这样生成。
                productionOrder.setStatus("planned");
                //获取汽车配置当前启用的生产工艺
                MesCarTechnologyQuery carTechnologyQuery=new MesCarTechnologyQuery();
                carTechnologyQuery.setCarModelConfig(carOrder.getCarModelConfig());
                carTechnologyQuery.setEnabled(true);//启用状态
                List<MesCarTechnology> carTechnologys = carTechnologyMapper.findAll(carTechnologyQuery);
                if(carTechnologys.size()==1){
                    productionOrder.setCarTechnology(carTechnologys.get(0));//设置当前生产工艺
                }else if(carTechnologys.size()>1){
                    throw new MyServiceException(String.format("生成失败：汽车配置%s当前有%d个启用的生产工艺，请先处理后再进行操作",carOrder.getCarModelConfig(),carTechnologys.size()));
                }else{
                    throw new MyServiceException(String.format("生成失败：汽车配置%s当前没有启用的生产工艺，请先启用再进行操作",carOrder.getCarModelConfig()));
                }
                //添加到集合中
                productionOrders.add(productionOrder);
            }
            //保存生产订单到数据库
            mapper.saveAllIn(productionOrders);
        }
        //3.将已经生成生产订单的商城订单变为生产状态。
        // 提取ID集合
        String[] orderIds = carOrders.parallelStream()
                .filter(order -> order != null && order.getId() != null)
                .map(ShopCarOrder::getId)
                .distinct()  // 去重
                .toArray(String[]::new);
        carOrderMapper.batchUpdateOrderStatusByIdIn("producing",orderIds);
        result=orderIds.length;
        return result;
    }

    @Override
    public int beginProduction(@NotEmpty(message = "操作失败：请选择要生产的订单")String[] orderIds) {
        if(orderIds!=null&&orderIds.length>0){
            for(String orderId:orderIds){
                MesProductionOrder productionOrder = mapper.findById(orderId);
                if(productionOrder!=null){
                    if(!productionOrder.getStatus().equals("planned")){
                        throw new MyServiceException(String.format("启动失败：VIN为%s的车辆无法转为生产状态，只有计划排产的订单才可以",productionOrder.getVin()));
                    }
                }else{
                    throw new MyServiceException(String.format("启动失败：订单号%s在系统中不存在",orderId));
                }
            }
        }
        return mapper.batchUpdateStatusByIdIn("in_progress",orderIds);
    }

    @Override
    public void changeProductionStatus(String orderId, String targetStatus) {
        MesProductionOrder productionOrder = mapper.findById(orderId);
        if(productionOrder==null){
            throw new MyWebException(String.format("操作失败：订单号%s在系统中不存在",orderId));
        }
        if(!MesConstant.MESPRODUCTIONORDER_STATUSLIST.contains(targetStatus)){
            throw new MyWebException(String.format("操作失败：订单状态%s在系统中不存在",targetStatus));
        }
        if(targetStatus.equals("paused")){
            if(!productionOrder.getStatus().equals("in_progress")) {
                throw new MyServiceException(String.format("操作失败：只有生产中的订单才能暂停",targetStatus));
            }
        }
        if(targetStatus.equals("in_progress")){//这里是恢复生产的意思
            if(!productionOrder.getStatus().equals("paused")) {//不用考虑plan状态
                throw new MyServiceException(String.format("操作失败：只有暂停生产的订单才能恢复生产",targetStatus));
            }
        }
        if(targetStatus.equals("cancelled")){
            if(!productionOrder.getStatus().equals("planned")) {
                throw new MyWebException(String.format("操作失败：只有处于计划生产的订单才能取消",targetStatus));
            }else{
                //如果生产订单取消，那么商品订单也会取消,联动修改
                ShopCarOrder carOrder = carOrderMapper.findByIdNoRelation(productionOrder.getShopCarOrder().getId());
                carOrder.setOrderStatus("cancelled");
                carOrder.setCancelledType("production_cancelled");//设置取消类型
                carOrder.setCancelledTime(new Date());//设置取消时间
                carOrderMapper.update(carOrder);
            }
        }
        //保存状态
        productionOrder.setStatus(targetStatus);
        mapper.update(productionOrder);
    }

    @Override
    public void inspectionProductionOrders(String orderId, Boolean auditResult, String auditNote) {
        MesProductionOrder productionOrder = mapper.findById(orderId);
        if(productionOrder==null){
            throw new MyWebException(String.format("操作失败：订单号%s在系统中不存在",orderId));
        }
        if(!productionOrder.getStatus().equals("completed")){
            throw new MyServiceException("操作失败：生产订单还没有完成，无法进行审核！");
        }
        if(productionOrder.getAuditResult()!=null&&productionOrder.getAuditResult()){
            throw new MyServiceException("操作失败：生产订单已经审核通过，无需在进行审核！");
        }
        if(auditResult){//如果审核通过
            //将商城订单状态改为完成状态
            ShopCarOrder shopCarOrder = carOrderMapper.findByIdNoRelation(productionOrder.getShopCarOrder().getId());
            shopCarOrder.setOrderStatus("produced");
            carOrderMapper.update(shopCarOrder);
        }
        //记录订单审核结果
        productionOrder.setAuditor(UserUtil.getLoginUser());
        productionOrder.setAuditResult(auditResult);
        productionOrder.setAuditNote(auditNote);
        mapper.update(productionOrder);
        //记录审核日志
        MesProductionOrderAuditLog productionOrderAuditLog=new MesProductionOrderAuditLog();
        productionOrderAuditLog.setId(IdUtil.fastSimpleUUID());
        productionOrderAuditLog.setProductionOrder(productionOrder);
        productionOrderAuditLog.setAuditor(UserUtil.getLoginUser());
        productionOrderAuditLog.setAuditResult(auditResult);
        productionOrderAuditLog.setAuditNote(auditNote);
        productionOrderAuditLogMapper.save(productionOrderAuditLog);
    }
}
